// pages/cart/cart.js
const app = getApp();

Page({
  data: {
    cartList: [], // 购物车列表
    isAllSelected: false, // 是否全选
    totalPrice: 0, // 总金额
    selectedCount: 0 // 选中商品数量
  },
  onLoad: function(options) {
    // 从全局获取购物车数据
    this.loadCartData();
  },
  onShow: function() {
    // 每次页面显示时刷新数据
    this.loadCartData();
  },

  // 加载购物车数据
  loadCartData: function() {
    const cartList = app.globalData.cartList || [];
    this.updateCartData(cartList);
    this.setData({
      cartList: cartList
    }, () => {
      this.calculateTotal();
    });
  },

  // 减少数量
  reduceNum: function(e) {
    const index = e.currentTarget.dataset.index;
    let cartList = this.data.cartList;
    if (cartList[index].num > 1) {
      cartList[index].num--;
      this.updateCartData(cartList);
    }
  },

  // 增加数量
  addNum: function(e) {
    const index = e.currentTarget.dataset.index;
    let cartList = this.data.cartList;
    cartList[index].num++;
    this.updateCartData(cartList);
  },

  // 更新购物车数据
  updateCartData: function(cartList) {
    // 更新全局数据
    app.globalData.cartList = cartList;
    // 更新页面数据
    this.setData({
      cartList: cartList
    }, () => {
      this.calculateTotal();
    });
  },

  // 切换单项选择状态
  toggleSelect: function(e) {
    const index = e.currentTarget.dataset.index;
    let cartList = this.data.cartList;
    cartList[index].selected = !cartList[index].selected;
    this.updateCartData(cartList);
  },

  // 切换全选状态
  toggleAllSelect: function() {
    const isAllSelected = !this.data.isAllSelected;
    let cartList = this.data.cartList;
    
    cartList.forEach(item => {
      item.selected = isAllSelected;
    });
    
    this.updateCartData(cartList);
  },

  // 计算总金额和选中数量
  calculateTotal: function() {
    let totalPrice = 0;
    let selectedCount = 0;
    let isAllSelected = true;
    
    this.data.cartList.forEach(item => {
      if (item.selected) {
        totalPrice += item.price * item.num;
        selectedCount++;
      } else {
        isAllSelected = false;
      }
    });
    
    this.setData({
      totalPrice: totalPrice.toFixed(2),
      selectedCount: selectedCount,
      isAllSelected: isAllSelected && this.data.cartList.length > 0
    });
  },

  // 去结算
  goToCheckout: function() {
    if (this.data.selectedCount === 0) {
      wx.showToast({
        title: '请选择要结算的商品',
        icon: 'none'
      });
      return;
    }
    
    // 获取选中的商品
    const selectedItems = this.data.cartList.filter(item => item.selected);
    console.log('传递到结算页的商品数据:', selectedItems); // 添加日志输出
    const itemsStr = encodeURIComponent(JSON.stringify(selectedItems));
    // 可以在这里处理结算逻辑，例如跳转到结算页面
    wx.navigateTo({
      url: `/pages/submitOrder/submitOrder?items=${itemsStr}`
    });
  },

  // 去首页
  goToIndex: function() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  }
});